package com.ruoyi.business.service.impl;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.weapp.WeAppConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@Service("WxSignService")
public class WxSignService {

    private static final Logger log = LoggerFactory.getLogger(WxSignService.class);

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RestTemplate restTemplate;

    public Map<String, String> sign(String url) {
        String wx_js_ticket = redisCache.getCacheObject("wx_js_ticket");
        if (StringUtils.isEmpty(wx_js_ticket)) {
            String accessToken = getAccessToken();
            String jsApiTicket = getJsApiTicket(accessToken);
            redisCache.setCacheObject("wx_access_token", accessToken, 7198, TimeUnit.SECONDS);
            redisCache.setCacheObject("wx_js_ticket", jsApiTicket, 7198, TimeUnit.SECONDS);
            wx_js_ticket = jsApiTicket;
        }
        Map<String, String> ret = sign(wx_js_ticket, url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        return ret;
    }

    public JSONObject httpsRequest(String url) {
        try {
            ResponseEntity<JSONObject> entity = restTemplate.getForEntity(url, JSONObject.class, (Object) null);
            return entity.getBody();
        } catch (Exception e) {
            log.error("http请求异常");
        }
        return new JSONObject();
    }

    /**
     * 获取接口访问凭证
     */
    public String getAccessToken() {
        //凭证获取(GET)
        String token_url =  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET" ;
        String requestUrl = token_url.replace( "APPID" , WeAppConfig.WX_APP_ID).replace( "APPSECRET" , WeAppConfig.WX_APP_SECRET);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl);
        String accessToken =  null ;
        if  ( null  != jsonObject) {
            try  {
                accessToken = jsonObject.getString( "access_token" );
            }  catch  (JSONException e) {
                // 获取token失败
                log.error( "获取token失败 errcode:{} errmsg:{}" , jsonObject.getString( "errcode" ), jsonObject.getString( "errmsg" ));
            }
        }
        return accessToken;
    }

    /**
     * 调用微信JS接口的临时票据
     *
     * @param access_token 接口访问凭证
     * @return
     */
    public String getJsApiTicket(String access_token) {
        String url =  "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi" ;
        String requestUrl = url.replace( "ACCESS_TOKEN" , access_token);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl);
        String ticket =  null ;
        if  ( null  != jsonObject) {
            try  {
                ticket = jsonObject.getString( "ticket" );
            }  catch  (JSONException e) {
                // 获取token失败
                log.error( "获取token失败 errcode:{} errmsg:{}" , jsonObject.getString( "errcode" ), jsonObject.getString( "errmsg" ));
            }
        }
        return ticket;
    }

    public Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId", WeAppConfig.WX_APP_ID);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
